package cn.tedu._04weibo.base.filters;

import cn.tedu._04weibo.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns ="/v1/vehicle/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
      log.debug("初始化...");
    }

    @Override
    public void destroy() {
        log.debug("销毁...");
    }

    /**
     * 过滤器的核心方法：
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录状态效验的过滤器...");
        //实现登录状态的效验
        //HttpServletRequest 和 ServletResponse 是父子关系
        HttpServletRequest  request = (HttpServletRequest) servletRequest;
        HttpServletResponse  response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO != null){//登录状态
            //放行
            //有此行代码，代表放行
            //无此行代码，代表拦截
            filterChain.doFilter(request,response);
        }else {
            response.sendRedirect("/login.html");
        }
    }
}
